import React, { useRef, useEffect } from 'react';
import echarts from 'echarts';
import 'echarts/lib/chart/line';
import moment from 'moment';

interface ILineProps {
  xLable: string[];
  data: {
    name: string;
    data: number[];
    lineColor: string;
    // areaColor: string[]; // 渐变颜色，第一位为最顶部颜色，第二位为最底部颜色
  }[]; // 数据
}

function Line(props: ILineProps) {
  const divEl = useRef(null);
  const { xLable, data } = props;
  const option: echarts.EChartOption = {
    grid: {
      containLabel: true,
      left: 0,
      right: 2,
      top: 40,
      bottom: 90
    },
    legend: {
      bottom: 0,
      icon: 'circle',
      textStyle: {
        color: '#686C78'
      },
      data: []
    },
    dataZoom: [
      {
        type: 'slider',
        backgroundColor: 'rgba(174, 212, 255, 0.1)',
        dataBackground: {
          lineStyle: {
            color: 'transparent'
          },
          areaStyle: {
            color: 'rgba(149, 179, 209, 0.4)'
          }
        },
        borderColor: 'transparent',
        handleStyle: {
          color: '#AED4FF'
        },
        bottom: 40,
        startValue: moment().subtract(8, 'days').format('YYYY-MM-DD')
      }
    ],
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        lineStyle: {
          type: 'dashed'
        }
      },
      backgroundColor: '#394255',
      padding: 8
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xLable,
      axisLabel: {
        color: '#999EA8',
        margin: 16,
        showMinLabel: false,
        showMaxLabel: false
      },
      axisTick: {
        show: false
      },
      axisLine: {
        show: false
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        margin: 16,
        color: '#999EA8'
      },
      axisTick: {
        show: false
      },
      axisLine: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: '#d8d8d8'
        }
      }
    },
    series: []
  };
  if (data.length) {
    option.legend!.data = data.map((item) => item.name);
    option.series = data.map((item) => ({
      type: 'line',
      name: item.name,
      data: item.data,
      itemStyle: {
        color: item.lineColor
      },
      lineStyle: {
        color: item.lineColor
      }
      // areaStyle: {
      //   color: {
      //     type: 'linear',
      //     x: 0,
      //     y: 0,
      //     x2: 0,
      //     y2: 1,
      //     colorStops: [
      //       {
      //         offset: 0,
      //         color: item.areaColor[0], // 0% 处的颜色
      //       },
      //       {
      //         offset: 1,
      //         color: item.areaColor[1], // 100% 处的颜色
      //       },
      //     ],
      //   },
      // },
    }));
  }
  useEffect(() => {
    const lineDom = echarts.init(divEl.current!);
    lineDom.setOption(option);
  });
  return <div ref={divEl} style={{ height: '100%', width: '100%' }} />;
}

export default Line;
